import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Button,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
// 导入图标组件
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import Channel from '@/components/Channel'
import styles from './index.module.scss'
import { ArticleStatus } from '@/utils/config'
import { getArticles, delArticle } from '@/api/articles'
import { Redirect } from 'react-router-dom/cjs/react-router-dom.min'

export default class Article extends Component {
  state = {
    articles: [],
    total: 0,
    loading: false,
  }
  // 筛选条件
  reqParams = {
    status: null,
    page: 1,
    per_page: 10,
    channel_id: null,
    begin_pubdate: null,
    end_pubdate: null,
  }
  // 列表的列配置
  columns = [
    {
      title: '封面',
      render(row) {
        return <img className="logo" src={row.cover.images[0]} alt="" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      render(row) {
        if (row.status === 1) {
          return <Tag color="lime">待审核</Tag>
        } else if (row.status === 2) {
          return <Tag color="green">审核通过</Tag>
        } else {
          return <Tag color="orange">草稿</Tag>
        }
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (row) => {
        return (
          <Space>
            {/* 修改 */}
            <Button
              onClick={() => this.handleEdit(row.id)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            />
            {/* 删除 */}
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => this.handleDelete(row.id)}
            />
          </Space>
        )
      },
    },
  ]

  // 获取文章列表数据
  getArticlesData = async () => {
    this.setState({
      loading: true,
    })
    // console.log(this.reqParams)
    // 获取文章列表
    const res = await getArticles(this.reqParams)
    // console.log(res.data.results)
    this.setState({
      articles: res.data.results,
      total: res.data.total_count,
      loading: false,
    })
  }
  // 页面渲染完毕请求数据
  componentDidMount() {
    // 好处：两个请求接口可以同时去请求服务器端
    this.getArticlesData()
  }
  render() {
    const { articles, total, loading } = this.state
    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          {/* 搜索 */}
          <Form initialValues={{ status: -1 }} onFinish={this.submitForm}>
            {/* 状态筛选 */}
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleStatus.map((item) => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {/* 频道筛选 */}
            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>
            {/* 日期筛选 */}
            <Form.Item label="日期" name="date">
              <DatePicker.RangePicker />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        {/* 列表 */}
        {!loading ? (
          <Card title={`根据筛选条件共查询到${total}条结果：`}>
            <Table
              // 给每一行加唯一标识，方面查找,id是唯一的
              rowKey="id"
              dataSource={articles}
              columns={this.columns}
              pagination={{
                position: ['bottomCenter'],
                total: total,
                current: this.reqParams.page,
                pageSize: this.reqParams.per_page,
                onChange: this.onChange,
              }}
            />
          </Card>
        ) : (
          // 数据因为网络原因未加载出来时显示组件
          <div className="loading"></div>
        )}
      </div>
    )
  }

  // 页面或者分页条数发生改变时触发
  onChange = (page, pageSize) => {
    this.reqParams.page = page
    this.reqParams.per_page = pageSize
    // 发起请求
    this.getArticlesData()
  }

  // 提交表单
  submitForm = (values) => {
    // 先清空筛选条件
    this.reqParams.status = null
    this.reqParams.begin_pubdate = null
    this.reqParams.end_pubdate = null
    this.reqParams.channel_id = null

    // 页码回归到第1页
    this.reqParams.page = 1
    // 组装筛选条件
    // 状态的筛选
    if (values.status === -1) {
      this.reqParams.status = null
    } else {
      this.reqParams.status = values.status
    }
    // 频道的判断
    if (values.channel_id) {
      this.reqParams.channel_id = values.channel_id
    }
    // 时间的判断
    if (values.date) {
      // 时间做处理
      // 注意：同一个日期的开始时间(00:00:00)和结束时间(23:59:59)
      this.reqParams.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      this.reqParams.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    }
    // 重新调接口获取数据
    this.getArticlesData()
  }
  // 删除文章
  handleDelete = (id) => {
    // 采用 confirm对话框
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章吗？',
      onOk: async () => {
        console.log(id)
        // 发送请求，删除文章
        await delArticle(id)
        // 重新获取用户列表
        this.getArticlesData()
        message.success('删除成功')
      },
    })
  }
  // 修改文章(和添加共用一个组件)
  handleEdit = (id) => {
    // 跳转到修改文章的路由地址
    this.props.history.push(`/home/publish/${id}`)
  }
}
